There are three ways to initialize a non-static data member in a class:
- With an in-class initializer (since C++11)
- In the initialization list of a constructor
- In the constructor body
You should use those methods in that order of preference. When applicable, in-class initializers are best, because they apply automatically to all
constructors of the class (except for default copy/move constructors and constructors where an explicit initialization for this member is provided).
But they can only be used for initialization with constant values.
If your member value depends on a parameter, you can initialize it in the constructor’s initialization list. If the initialization is complex, you
can define a function to compute the value, and use this function in the initializer list.
Initialization in the constructor body has several issues. First, it’s not an initialization, but an assignment. Which means it will not work with
all data types (const-qualified members, members of reference type, member of a type without default constructor…). And even if it works, the member
will first be initialized, then assigned to, which means useless operations will take place. To prevent "use-before-set" errors, it’s better to
immediately initialize the member with its real value.
It’s hard to find a good example where setting the value of a member in the constructor would be appropriate. One case might be when you assign to
several data members in one operation. As a consequence constructor bodies are empty in many situations.
This rules raises an issue in two conditions:
- When you assign a value to a member variable in the body of a constructor.
- When you default-initialize in an initializer list a member variable, that would be value-initialized by default
- For C++11 or later, when you initialize a member variable in the initializer list of a constructor, but could have done so directly in the
class:
- The variable has either no in-class initializer, or an in-class initializer with the same value as in the constructor
- The initial value does not depend on a constructor parameter
Noncompliant code example
class S {
int i1;
int i2;
int i3;
public:
S( int halfValue, int i2 = 0) : i2(i2), i3(42) { // Noncompliant for i1 and i3, compliant for i2
this->i1 = 2*halfValue;
}
};
Compliant solution
class S {
int i1;
int i2;
int i3 = 42; // In-class initializer
public:
S( int halfValue, int i2 = 0 ) : i1(2*halfValue), i2(i2) {} // Compliant
};